package com.appspot.zcmjqm.service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.appspot.zcmjqm.app.model.Consult;
import com.appspot.zcmjqm.app.model.category.ConsultingCategory;
import com.appspot.zcmjqm.app.model.quote.ConsultQuote;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@Service
public class ConsultServiceJPAImpl implements ConsultService {
	
	@Autowired
	private EntityManager entityManager;
	
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	@Transactional
	public List<ConsultingCategory> getAllCategories() {
		List<?> l = entityManager.createQuery("select from ConsultingCategory").getResultList();
		List<ConsultingCategory> categories = new ArrayList<ConsultingCategory>();
		for (Object o : l) {
			categories.add((ConsultingCategory) o);
		}
		return categories;
	}

	@Transactional
	public List<Consult> getByCategory(String categoryKey) {
		ConsultingCategory consultingCategory = new ConsultingCategory();
		Key k = KeyFactory.stringToKey(categoryKey);
		consultingCategory.setKey(k);
		Query query = entityManager.createQuery("select from Consult where consultingCategory = :cat");
		query.setParameter("cat", consultingCategory);
		List<?> l = query.getResultList();
		List<Consult> consults = new ArrayList<Consult>();
		for (Object o : l) {
			consults.add((Consult) o);
		}
		return consults;
	}

	@Transactional
	public Consult getById(String key) {
		Key k = KeyFactory.stringToKey(key);
		return entityManager.find(Consult.class, k);
	}

	@Transactional
	public void saveQuote(ConsultQuote consultQuote) {
		entityManager.merge(consultQuote);
	}
	
}